package com.zhuang.springbootnio.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolConfig {

    // 获取CPU核心数
    private static final int CPU_CORES = Runtime.getRuntime().availableProcessors();

    // IO密集型任务线程池
    public static ExecutorService ioThreadPool = new ThreadPoolExecutor(
            20,                          // 核心线程数：IO密集型可设较大值
            50,                          // 最大线程数
            60L,                         // 空闲线程存活时间
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000),  // 任务队列，设置较大容量
            new CustomThreadFactory("io-pool"), // 自定义线程工厂
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
    );

    // CPU密集型任务线程池
    public static ExecutorService cpuThreadPool = new ThreadPoolExecutor(
            CPU_CORES + 1,               // 核心线程数：CPU核心数+1
            CPU_CORES * 2,               // 最大线程数
            30L,                         // 空闲线程存活时间
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(500),   // 任务队列
            new CustomThreadFactory("cpu-pool"),
            new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
    );

    // 自定义线程工厂，设置线程名称便于监控
    static class CustomThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicInteger threadId = new AtomicInteger(1);

        public CustomThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, namePrefix + "-thread-" + threadId.getAndIncrement());
            thread.setDaemon(true); // 设置为守护线程
            return thread;
        }
    }
}
